//
//  ThirdAccountVC.swift
//  LeGou
//
//  Created by lxm on 2022/8/1.
//

import UIKit
class ThirdAccountVC: ZMViewController, UITableViewDelegate, UITableViewDataSource {
    //MARK: --------------------属性--------------------
    let padding : CGFloat = 15
    
    var data : [[(title : String, subTitle : String, icon : Bool, id : Int)]] = [
        [
         (title : "绑定支付宝账号", subTitle : "未绑定", icon : true, id : 0),
         (title : "绑定微信账号", subTitle : "未绑定", icon : true, id : 1),
         (title : "绑定银行卡", subTitle : "未绑定", icon : true, id : 1)
        ]
    ]
    
    let walletInfo = ZMUtil.fastNilBehavior(type: MineModels.WalletInfo.self)

    //MARK: --------------------UI控件--------------------
    let tableView = UITableView(frame: CGRect.zero, style: .plain).then { t in
        t.separatorStyle = .none
        t.estimatedSectionFooterHeight = 0.01
        t.estimatedSectionHeaderHeight = 0.01
        t.sectionFooterHeight = 0.01
        t.sectionHeaderHeight = 0.01
    }
    
    let loading = XMLoadingView()

    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loading.showInView(fatherView: view)
        loadInfo()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        title = "第三方账户"
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        
        let v = UIView()
        tableView.tableFooterView = v
        tableView.backgroundColor = "#F5F5F5".zm.hex()
        view.backgroundColor = "#F5F5F5".zm.hex()
        
        v.frame = CGRect(x: 0, y: 0, width: SCREEN_W, height: 120)
        v.backgroundColor = .clear

        tableView.zm.register(nibName: "SettingCell", reuserId: "SettingCell")
    }
    
    func addConstraints() {
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(padding)
            make.right.equalToSuperview().offset(-padding)
            make.top.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        ZMNotification.shard.subject.subscribe(onNext:{ [unowned self] resp in
            switch resp {
                case .bindThirdSuccess:
                self.loadInfo()
            default:break
            }
        }).disposed(by: disposeBag)
        
        walletInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
//            self.balanceLabel.text = "余额 ￥\(resp.balance.zm.toString(keep: 2))"
            self.data = [[
                 (title : "绑定支付宝账号" , subTitle : resp.alipayUserId.count > 0 ? "已绑定" : "未绑定", icon : true, id : 0),
                 (title : "绑定微信账号" , subTitle : resp.wxAccount.count > 0 ? "已绑定" : "未绑定", icon : true, id : 1),
                 (title : "绑定银行卡" , subTitle : resp.bankNo.count > 0 ? "已绑定" : "未绑定", icon : true, id : 2)
                ]]
            tableView.reloadData()
        }).disposed(by: disposeBag)
        
        ZMNotification.shard.subject.subscribe(onNext:{ [unowned self] resp in
            switch resp {
                case .aliAuthSuccess(let map):
                print(map)
                print(JSON(map))
                ZMToast.showActivity()
                self.parseAndRequestAli(dicStr: JSON(map)["result"].stringValue)
                break
                default:break
            }
        }).disposed(by: disposeBag)
    }
    
    func parseAndRequestAli(dicStr : String) {
        if let authCode = getQueryDic(query: dicStr)["auth_code"]  {
            MineAPI.bindAliInfo(["code" : authCode]).rxRequest(type: Bool.self).subscribe(onNext:{ [unowned self] resp in
                if resp {
                    ZMToast.showToast(title: "绑定成功")
                    ZMNotification.shard.subject.onNext(.bindThirdSuccess)
                } else {
                    ZMToast.showToast(title: "绑定失败")
                }
            }).disposed(by: disposeBag)
        } else {
            ZMToast.showToast(title: "获取授权信息失败")
        }
    }
    
    func getQueryDic(query:String) -> [String : String] {
//        TestNetTool.shareInstance()?.addRecordUrl(query, param: [:], method: "query", respons: [:])
        let array = query.split(separator: "&").map({"\($0)"})
        var r = [String : String]()
        for dicStr in array {
            let dicArray = dicStr.split(separator: "=").map({"\($0)"})
            if dicArray.count == 2 {
                r[dicArray[0]] = dicArray[1]
            }
        }
        TestNetTool.shareInstance()?.addRecordUrl(query, param: [:], method: "query", respons:r)
        return r
    }
    
    func loadInfo() {
        MineAPI.walletInfo([:]).rxRequest(type: MineModels.WalletInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.walletInfo.accept(resp)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }

    //MARK: --------------------delegate--------------------
    func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data[section].count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 16
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 48
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let v = UIView()
        v.backgroundColor = .red
        return v
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SettingCell") as! SettingCell
        let data = data[indexPath.section][indexPath.row]
        cell.titleLabel.text = data.title
        cell.subLabel.text = data.subTitle
        cell.rightIcon.isHidden = !data.icon
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let allCount = self.data[indexPath.section].count
        let current = indexPath.row
        if allCount == 1 {
            ZMUtil.clipCircle(view: cell, Corner: [.topLeft, .topRight, .bottomLeft, .bottomRight], radius: 12)
        } else {
            if current == 0 {
                ZMUtil.clipCircle(view: cell, Corner: [.topLeft, .topRight,], radius: 12)
            } else if current == allCount - 1 {
                ZMUtil.clipCircle(view: cell, Corner: [.bottomLeft, .bottomRight], radius: 12)
            } else {
                cell.layer.mask = nil
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let info = self.walletInfo.value else {return}
        let item = data[indexPath.section][indexPath.row]
        if item.id == 0 {
            if info.alipayUserId.count > 0 {
                // 绑定了
                let vc = AccountBindDetialVC()
                vc.type = 1
                vc.nickname = info.alipayName
                vc.wxOpenId = info.alipayUserId
                self.navigationController?.pushViewController(vc, animated: true)
            } else {
                // 未绑定
                if !DebounceTool.shard.debounce(DebounceTool.THIRDE_LOGIN) {return}
                getAlipayInfo()
            }
        } else if item.id == 1 {
            if info.wxAccount.count > 0 {
                // 绑定了微信
                let vc = AccountBindDetialVC()
                vc.type = 0
                vc.nickname = info.wxName
                vc.wxOpenId = info.wxAccount
                self.navigationController?.pushViewController(vc, animated: true)
            } else {
                // 未绑定
                if !DebounceTool.shard.debounce(DebounceTool.THIRDE_LOGIN) {return}
                ZMShareManager.authorize(0) { user in
                    if let user = user, let uid = user.uid  {
                        self.bindWx(nickname: user.nickname, wxOpenId: uid)
                    } else {
                        ZMToast.showToast(title: "授权失败")
                    }
                }
            }
        } else if item.id == 2 {
            if LoginService.shared.checkRealName() == false {return}
            // 银行卡信息
            if info.bankNo != "" {
                // 绑定了
                let vc = BankInfoVC()
                vc.info = info
                self.navigationController?.pushViewController(vc, animated: true)
            } else {
//                let vc = TradeFroget()
//                vc.type = 1
//                self.navigationController?.pushViewController(vc, animated: true)
                self.navigationController?.pushViewController(BankInfoInputVC(), animated: true)
            }
        }
    }
    
    func bindAlipay() {
        
    }
    
    func getAlipayInfo() {
        ZMToast.showActivity()
        MineAPI.getAliLoginParam.rxRequest(type: String.self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            AlipaySDK.defaultService().auth_V2(withInfo: resp, fromScheme: AliScheme) { map in
            }
        }).disposed(by: disposeBag)
    }
    
    func bindWx(nickname : String, wxOpenId : String) {
        MineAPI.wxBind(["wxName" : nickname, "wxOpenId" : wxOpenId]).rxRequest(type: Any.self).subscribe(onNext:{ [unowned self] resp in
            ZMNotification.shard.subject.onNext(.bindThirdSuccess)
            ZMToast.showToast(title: "已绑定")
        }).disposed(by: disposeBag)
    }
}
